package yxy.game.pm2.command.hero;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.EquipPosition;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.hero.HeroHandle;

/** 武将装备 武将换装备 */
@MessageType(proto = Command.HeroEquipChange, classtype = HeroMessage.HeroEquipChangeRequest.class)
public class CMD_HeroEquipChange extends Command<HeroMessage.HeroEquipChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.HeroEquipChangeRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();
		int equippos = request.getEquippos();
		int equipid = request.getEquipid();

		HeroMessage.HeroEquipChangeResponse.Builder response = HeroMessage.HeroEquipChangeResponse.newBuilder();

		try {
			if (Hero.lockHero(playerCode)) {

				EquipPosition pos = EquipPosition.forNumber(equippos);
				if (pos == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}

				HeroHandle heroHandle = new HeroHandle();
				Hero hero = heroHandle.getHero(playerCode, code);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}

				Result result = heroHandle.changeEquip(playerCode, hero, pos, equipid);
				if (!result.equals(Result.Success)) {
					send(messageSource, response, result);
					return;
				}
				HeroMessage.HeroInfo heroInfo = heroHandle.getHeroInfo(playerCode, hero);
				response.setInfo(heroInfo);
				send(messageSource, response, result);

				heroHandle.heroTipNotification(playerCode, hero);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			Hero.unlockHero(playerCode);
		}
	}

	private void send(MessageSource messageSource, HeroMessage.HeroEquipChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}